window.onload = function () {
    // getFriendList();
    userCenter();
    var a = localStorage.getItem("token");
    if(a == null){
        $(".login").show();
    }
}

function show(el) {
    $(".login,.register,.insert,.do-you-agree").not(el).hide(200);
    $(el).show();
}

function hide(el) {
    if (el == ".exit"){
        $(".operation").removeClass("black");
        $('.operation:first-of-type').addClass("black");
        $(".box-right-top-operation").text("");
        $(".box-right-top-operation").text($('.operation:first-of-type').text());
    }
    $(el).hide();
}

$(function () {

    // setInterval(()=>{
    //     if($(".friend-name").attr("friend-id") != undefined){
    //         getContent($(".friend-name").attr("friend-id"),localStorage.getItem("userId"),null,1);
    //     }
    // },10000);
    // $(".operation").click(function() {
    //     $(".operation").removeClass("black");
    //     $(this).addClass("black");
    //     $(".box-right-top-operation").text("");
    //     $(".box-right-top-operation").text($(this).text());
    // });
    var a = localStorage.getItem("token");
    if(a != null){
        $(".login-box").hide();
    }
    //把昵称获取到放在页面
    var nickname = localStorage.getItem("nickname");
    $("#username").text(nickname);
    $("#search").click(function () {
        //获取手机号
        const phone = $("#input-phone").val();
        if (phone == "") {
            alert("请输入手机号");
            return false;
        }
        //发送请求
        $.ajax({
            url: "/users-info/getPhone/" + phone,
            type: "get",
            headers: {
                // 携带token发生请求
                "token": localStorage.getItem("token")
            },
            dataType: "json",
            success: function (res) {

                $(".box-left-center ul").empty();
                //遍历结果到userInfoList里面
                var html = "";
                for (var i = 0; i < res.data.length; i++) {
                    html += "<li class='phone-result'><p>" + res.data[i].nickname + " </p><button onclick='addFriend(" + res.data[i].userId + ")'>添加好友</button></li>";
                }
                $(".box-left-center ul").html(html);
            },
            error: function (res) {
                alert(res.responseJSON.message);
                $(".login").show();
            }
        })
    })
    // 登录
    $("#login").click(function () {
        const username = $("#username").val();
        const password = $("#password").val();
        let data = {"password": password, "username": username};
        $.ajax({
            type: "post",
            url: "/users-info/login",
            data: JSON.stringify(data),
            contentType: "application/json",
            success: function (data) {//成功的响应
                if(data.code == 86203){
                    alert(data.msg);
                }
                var token = data.data.token;
                //localStorage 保存token
                localStorage.setItem("token", token);
                localStorage.setItem("nickname", data.data.nickname);
                localStorage.setItem("userId", data.data.userId);
                $("#username").text(data.data.nickname);
                $(".login-box").hide();
                //去触发长连接
                loginSuccess();
                userCenter();
            },
            error: function (data) {//失败的响应
                //从异常拿数据
                var errorList = data.responseJSON.data;
                $("#error-msg").html("");
                //errorList用p标签包裹起来
                for (var i = 0; i < errorList.length; i++) {
                    $("#error-msg").append("<p>" + errorList[i] + "</p>");
                }
                console.log(data);
            }
        });
    })
})

// 个人信息
function userCenter() {
    $.ajax({
        type: "POST",
        url: "users-info/center",
        success: function (res) {
            let center_html = "<li>昵称：" + res.data.nickname + "</li><br><li>账号：" + res.data.username + "</li>";
            $(".user-info-name").append(center_html);
        },
        error: function (err) {
            console.error(err);
        }
    })
}

// 加载申请好友列表
function getFriendList() {
    const token = localStorage.getItem("token");
    $.ajax({
        url: 'users-friend/getFriendByUserId', // 替换为您的后端API用户信息端点
        type: 'GET',
        headers: {
            token: token
        },
        contentType: 'application/json',
        success: function (res) {
            console.log(res)
            const num = res.data.length;
            if (num > 0) {
                $(".friend-num").text(num);
                $(".friend-num").css("display", "inline-block");
            }
            let html = '';
            for (let i = 0; i < num; i++) {
                html = "<li>" + res.data[i].nickname + " <button class='my-friends-yes' info-id=" + res.data[i].id + ">同意</button><button class='my-friends-no' info-id=" + res.data[i].id + ">拒绝</button></li>";
                $("#confirm-friend").append(html);
            }
            setTimeout(() => {
                $(".my-friends-yes").on("click", function () {
                    friendHandling($(this).attr("info-id"), 1);
                });
                $(".my-friends-no").on("click", function () {
                    friendHandling($(this).attr("info-id"), 2);
                });
            }, 1000);
        },
        error: function (error) {
            console.error(error);
        }
    });
}

// 加载好友列表
function getFriendTable() {
    $.ajax({
        type: "get",
        url: "users-friend/findFriendByUserId",
        headers: {
            token: localStorage.getItem("token")
        },
        contentType: "application/json",
        success: function (res) {
            $(".box-left-center ul").empty();
            if (res.code == 200) {
                let html = "";
                for (let i = 0; i < res.data.length; i++) {
                    html = "<li class='friend-nickname' friend-id=" + res.data[i].id + " groups-id=''>" + res.data[i].nickname + "</li>";
                    $(".box-left-center ul").append(html);
                }
                $(".friend-nickname").click(function () {
                    $(".friend-nickname").removeClass("grey");
                    $(this).addClass("grey");
                    $(".friend-name").attr("friend-id",$(this).attr("friend-id"));
                    $(".friend-name").text($(this).text());
                    getContent($(this).attr("friend-id"),localStorage.getItem("userId"),null,1);
                })
            }
        }
    })
}

// 添加好友
function addFriend(friendId) {
    const token = localStorage.getItem("token");
    $.ajax({
        url: 'users-friend/add/' + friendId, // 替换为您的后端API用户信息端点
        type: 'post',
        headers: {
            token: token
        },
        contentType: 'application/json',
        success: function (res) {
            if (res.code == 200) {
                alert("添加成功")
            } else {
                alert("添加失败")
            }
        },
        error: function (error) {
            console.error(error);
        }
    });
}

$(".box-left-center ul li").click(function () {
    $(".friend-name").attr("friend-id",$(this).attr("friend-id"));
    $(".friend-name").text($(this).text());
    getContent($(this).attr("friend-id"),localStorage.getItem("userId"),null,1);
})
// 更新好友
function friendHandling(id, status) {
    $.ajax({
        type: "post",
        url: "users-friend/friendReview",
        contentType: "application/json",
        headers: {
            "token": localStorage.getItem("token")
        },
        data: JSON.stringify({
            id: id,
            status: status
        }),
        success: function (res) {
            console.log(res)
            if (res.code == 200) {
                alert("同意");
                getFriendList();
            }
        },
        error: function (error) {
            console.error(error);
        }
    })
// 注册
    $("#register").click(function () {
        var username = $("#register-nickname").val();
        var password = $("#register-password").val();
        var phone = $("#register-phone").val();
        $.ajax({
            url: "/users-info/add",
            type: "post",
            contentType: "application/json",
            data: JSON.stringify({
                "nickname": username,
                "password": password,
                "phone": phone
            }),
            success: function (data) {
                if (data.code == 200) {
                    alert("注册成功");
                    //清除输入框
                    $("#register-nickname").val("");
                    $("#register-password").val("");
                    $("#register-phone").val("");
                } else {
                    alert(data.msg);
                }
            }
        })
    })
}


//退出登录
function loginOut() {
    //完成服务器token的过期
    $.ajax({
        url: "/users-info/loginOut",
        type: "post",
        contentType: "application/json",
        headers: {
            "token": localStorage.getItem("token")
        },
        success: function (data) {
            //完成本地清除
            localStorage.removeItem("token");
            localStorage.removeItem("nickname")
            window.location.reload();
        },
        error: function (data) {
            //退出登录都报错就直接删除token
            localStorage.removeItem("token");
            localStorage.removeItem("nickname")
            window.location.reload();
        }
    })
}
function getContent(friendId,userId,groupsId,flag) {
    $.ajax({
        type: "post",
        url:"chat-messages/getContent",
        contentType: "application/json",
        data:JSON.stringify({
            friendId:friendId,
            userId:userId,
            groupsId:groupsId,
            flag: flag
        }),
        success:function (res){
            if (res.code == 200){
                console.log(res)
                $(".scrollable-list").empty();
                let html = "";
                for (let i = 0;res.data.length > i;i++) {
                    if (res.data[i].userId == localStorage.getItem("userId")) {
                        html += "<li class=\"personal\"><p><i>" + res.data[i].nickname + "</i><span>" + res.data[i].createTime + "</span></p><p>" + res.data[i].content + "</p></li>";
                    }else {
                        html += "<li><p><i>" + res.data[i].nickname + "</i><span>" + res.data[i].createTime + "</span></p><p>" + res.data[i].content + "</p></li>";
                    }
                }
                $(".scrollable-list").append(html);
            }// 假设 res.data 是从某个异步操作（如 AJAX 请求）中获得的
            if (Array.isArray(res.data) && res.data.length !== 0) {
                // 确保 .scrollable-list 和其内部的 li 元素存在
                const $scrollableList = $('.scrollable-list');
                const $lastLi = $scrollableList.find('li:last-child');

                if ($scrollableList.length && $lastLi.length) {
                    // 计算最后一个 li 元素的顶部偏移量，相对于 .scrollable-list 的顶部
                    const lastLiOffsetTop = $lastLi.offset().top - $scrollableList.offset().top;

                    // 确保 lastLiOffsetTop 是一个有效的数字
                    if (!isNaN(lastLiOffsetTop)) {
                        // 滚动到最后一个 li 元素的位置
                        $scrollableList.scrollTop(lastLiOffsetTop);
                    } else {
                        console.error('无法计算最后一个 li 元素的偏移量');
                    }
                } else {
                    console.error('.scrollable-list 或其内部的 li 元素不存在');
                }
            } else {
                console.error('res.data 不是数组或长度为0');
            }
        },
        error: function () {
            alert("error")
        }
    })
}

function addContent(friendId, userId, groupsId, content, flag) {

    $.ajax({
        type: 'POST',
        url: "chat-messages/add",
        contentType: 'application/json',
        data: JSON.stringify({
            friendId:friendId,
            userId:userId,
            groupsId:groupsId,
            content: content,
            flag:flag
        }),
        success: function (res) {
            if (res.code == 200) {
                if (groupsId != null) {
                    getContent(null, userId, groupsId, 2);
                }else {
                    getContent(friendId,userId,null,1);
                }
            }
        },
        error: function () {
            alert("error")
        }
    })
}
$(document).ready(function () {
    $('#sendButton').click(function () {
        var message = $('#messageInput').val();
        if ($.trim(message) !== '') {
            // 在这里处理发送消息的逻辑，例如通过WebSocket或AJAX发送到服务器
            console.log('发送消息:', message);
            if (message.length < 200) {
                if ($.trim(message) != '') {
                    if ($(".friend-name").attr("friend-id") != null) {
                        addContent($(".friend-name").attr("friend-id"),localStorage.getItem("userId"),null,message,1);
                    }else {
                        addContent(null,localStorage.getItem("userId"),$(".friend-name").attr("groups-id"),message,1);
                    }
                }
            }else{
                alert("内容超过限定长度");
            }
            // 清空输入框以便输入新消息
            $('#messageInput').val('');
        } else {
            alert('请输入消息内容！');
        }
    });
    $('#messageInput').keydown(function (e) {
        var message = $(this).val();
        var isCtrlKeyDown = e.ctrlKey || e.metaKey; // metaKey 用于Mac上的Command键
        var keyCode = e.which || e.keyCode;
        if (keyCode === 13) { // 回车键的键码是13
            e.preventDefault();
            if (isCtrlKeyDown) {
                // Ctrl+回车，插入换行符
                $(this).val(message + '\n'); // 插入换行符
            } else {
                // 普通回车，发送消息
                if ($.trim(message) !== '') {
                    // 在这里处理发送消息的逻辑，例如通过WebSocket或AJAX发送到服务器
                    console.log('发送消息:', message);
                    if (message.length < 200) {
                        if ($.trim(message) != '') {
                            if ($(".friend-name").attr("friend-id") != null) {
                                addContent($(".friend-name").attr("friend-id"), localStorage.getItem("userId"), null, message, 1);
                            } else {
                                addContent(null, localStorage.getItem("userId"), $(".friend-name").attr("groups-id"), message, 1);
                            }
                        }
                    } else {
                        alert("内容超过限定长度");
                    }
                    // 清空输入框以便输入新消息
                    $('#messageInput').val('');
                } else {
                    alert('请输入消息内容！');
                }
            }
            e.preventDefault(); // 阻止默认的提交行为
        }

    });
});